import Foundation
import StoreKit

// 定义支付状态枚举
enum PaymentStatus {
    case purchasing // 正在购买
    case purchased // 购买成功
    case failed(String) // 购买失败
    case restored(String) // 恢复购买成功，产品 ID
    case deferred // 购买延迟处理
    case invalidProductID // 未找到有效的产品
    case unknown // 未知交易状态
}

// 定义内购管理类
class PaymentManager: NSObject, ObservableObject, SKProductsRequestDelegate, SKPaymentTransactionObserver {
    @Published var currentPaymentStatus: PaymentStatus = .unknown
    var purchaseCompletion: ((PaymentStatus) -> Void)?

    override init() {
        super.init()
        SKPaymentQueue.default().add(self)
    }

    deinit {
        SKPaymentQueue.default().remove(self)
    }

    // 直接根据产品 ID 发起购买
    func purchaseProduct(withIdentifier productIdentifier: String, completion: @escaping (PaymentStatus) -> Void) {
        purchaseCompletion = completion
        let productIdentifiers = Set([productIdentifier])
        let request = SKProductsRequest(productIdentifiers: productIdentifiers)
        request.delegate = self
        request.start()
    }

    // 恢复购买
    func restorePurchases(completion: @escaping (PaymentStatus) -> Void) {
        purchaseCompletion = completion
        // 先清空可能的旧回调，避免多回调干扰
        purchaseCompletion?(currentPaymentStatus)
        SKPaymentQueue.default().restoreCompletedTransactions()
    }

    // 处理产品请求结果
    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        if let product = response.products.first {
            let payment = SKPayment(product: product)
            SKPaymentQueue.default().add(payment)
            DispatchQueue.main.async {
                self.currentPaymentStatus = .purchasing
                self.purchaseCompletion?(.purchasing)
            }
        } else {
            for invalidIdentifier in response.invalidProductIdentifiers {
                showLog("Invalid product identifier: \(invalidIdentifier)")
            }
            DispatchQueue.main.async {
                self.currentPaymentStatus = .invalidProductID
                self.purchaseCompletion?(.invalidProductID)
            }
        }
    }

    // 处理交易结果（关键修复点）
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction in transactions {
            switch transaction.transactionState {
            case .purchased:
                handlePurchased(transaction: transaction)
            case .failed:
                handleFailed(transaction: transaction)
            case .restored:
                handleRestored(transaction: transaction)
            case .deferred:
                currentPaymentStatus = .deferred
                purchaseCompletion?(.deferred)
            case .purchasing:
                currentPaymentStatus = .purchasing
                purchaseCompletion?(.purchasing)
            @unknown default:
                currentPaymentStatus = .unknown
                purchaseCompletion?(.unknown)
            }
        }
    }

    // MARK: - 新增交易状态处理方法（解耦逻辑）
    private func handlePurchased(transaction: SKPaymentTransaction) {
        currentPaymentStatus = .purchased
        SKPaymentQueue.default().finishTransaction(transaction)
        purchaseCompletion?(.purchased)
    }

    private func handleFailed(transaction: SKPaymentTransaction) {
        let errorMessage = transaction.error.map {
            if let skError = $0 as? SKError {
                return skError.localizedDescription
            }
            return "未知错误"
        } ?? "未知错误"
        currentPaymentStatus = .failed(errorMessage)
        SKPaymentQueue.default().finishTransaction(transaction)
        purchaseCompletion?(.failed(errorMessage))
    }

    private func handleRestored(transaction: SKPaymentTransaction) {
        // 恢复购买的核心逻辑：从 originalTransaction 获取产品 ID
        let productIdentifier = transaction.original?.payment.productIdentifier ?? "未知产品"
        currentPaymentStatus = .restored(productIdentifier)
        SKPaymentQueue.default().finishTransaction(transaction)
        purchaseCompletion?(.restored(productIdentifier)) // 显式传递产品 ID
    }

    // MARK: - 恢复购买专用回调（关键修复点）
    func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
        // 处理恢复完成但无有效交易的情况（比如用户从未购买过）
        if queue.transactions.isEmpty {
            let errorMessage = "没有可恢复的购买记录"
            currentPaymentStatus = .failed(errorMessage)
            purchaseCompletion?(.failed(errorMessage))
            return
        }
        // 如有需要可在此统一处理所有恢复的交易
    }

    func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
        // 处理恢复购买过程中发生的错误（如网络问题）
        let errorMessage = error.localizedDescription
        currentPaymentStatus = .failed(errorMessage)
        purchaseCompletion?(.failed(errorMessage))
    }
}
